﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Landscape.Examples.MVC.Controllers {
    public class AuthController : Controller {
        public ActionResult Login() {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(Server.MapPath("~/Website.xml"));
            ViewData.Model = doc;
            ViewData["formAction"] = Url.Action("login", "auth");
            return View();
        }

        [HttpPost]
        public ActionResult Login(FormCollection form)  {
            string login = !string.IsNullOrEmpty(form["login"]) ? form["login"] : null;
            string password = !string.IsNullOrEmpty(form["password"]) ? form["password"] : null;
            if(login == null || password == null){
                ViewData["formError"] = "You must supply your credentials to sign in";
                return Login();
            }else if(login != "nobody@example.net" || password != "password"){
                ViewData["formError"] = "Invalid credentials. Please try again";
                return Login();        
            }else{
                Session["loginName"] = login;
                return RedirectToAction("dashboard");
            }
        }

        public ActionResult Dashboard() {
            if (Session["loginName"] == null) {
                return RedirectToAction("login");
            }
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(Server.MapPath("~/Website.xml"));
            ViewData.Model = doc;
            ViewData["loginName"] = Session["loginName"];
            ViewData["logoutLink"] = Url.Action("logout", "auth");
            return View();
        }

        public ActionResult Logout() {
            if (Session["loginName"] == null) {
                return RedirectToAction("login");
            }
            Session.Remove("loginName");
            return RedirectToAction("login");
        }
    }
}
